package com.leyou.search.service.impl;

import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.item.pojo.SpecParam;
import com.leyou.search.clients.BrandClient;
import com.leyou.search.clients.CategoryClient;
import com.leyou.search.clients.SpecClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.search.utils.SearchRequest;
import com.leyou.search.utils.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private SpecClient specClient;

    @Override
    public SearchResult search(SearchRequest searchRequest) {
        //创建查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //这里的key就是用户输入的要搜索的内容
        String key = searchRequest.getKey();
        if (StringUtils.isBlank(key)) {
            return null;
        }

        //调用构建的方法,返回一个布尔的查询条件对象
        QueryBuilder query = buildBasicQueryWithFilter(searchRequest);
        //添加查询条件
        queryBuilder.withQuery(query);
        queryBuilder.withPageable(PageRequest.of(searchRequest.getPage() - 1, searchRequest.getSize()));
        if (StringUtils.isNotBlank(searchRequest.getSortBy())) {
            queryBuilder.withSort(SortBuilders.fieldSort(searchRequest.getSortBy()).order(searchRequest.getDescending() ? SortOrder.DESC : SortOrder.ASC));
        }
        List<Long> cids = new ArrayList<>();
        List<Long> bids = new ArrayList<>();

        // 聚合
        String categoryAggName = "category"; // 商品分类聚合名称
        String brandAggName = "brand"; // 品牌聚合名称
        queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("cid3"));
        queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId"));

        //执行查询条件
        AggregatedPage<Goods> goodsPage = (AggregatedPage<Goods>) goodsRepository.search(queryBuilder.build());
        LongTerms categoryTerms = (LongTerms) goodsPage.getAggregation(categoryAggName);
        LongTerms brandTerms = (LongTerms) goodsPage.getAggregation(brandAggName);

        //获取桶并遍历添加到cids和bids集合中
        categoryTerms.getBuckets().forEach(bucket -> cids.add(bucket.getKeyAsNumber().longValue()));
        brandTerms.getBuckets().forEach(bucket -> bids.add(bucket.getKeyAsNumber().longValue()));
        List<Brand> brands = this.brandClient.queryBrandByIds(bids);
        List<Category> categories = this.categoryClient.queryCategoryByIds(cids);
        List<Map<String, Object>> specs = null;
        if (categories.size() == 1) {
            specs = getSpecs(categories.get(0).getId(), query);
        }
        return new SearchResult(goodsPage.getTotalElements(), new Long(goodsPage.getTotalPages()), goodsPage.getContent(), categories, brands, specs);
    }

    private List<Map<String, Object>> getSpecs(Long id, QueryBuilder query) {
        ArrayList<Map<String, Object>> specList = new ArrayList<>();
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //先根据查询条件进行查询
        queryBuilder.withQuery(query);
        List<SpecParam> specParams = this.specClient.querySpecParam(null, id, true);

        specParams.forEach(specParam ->
                queryBuilder.addAggregation(AggregationBuilders.terms(specParam.getName()).field("specs." + specParam.getName() + ".keyword")));
        AggregatedPage<Goods> page = (AggregatedPage<Goods>) this.goodsRepository.search(queryBuilder.build());

        specParams.forEach(specParam -> {
            String name = specParam.getName();
            //根据聚合名称获取聚合结果
            StringTerms stringTerms = (StringTerms) page.getAggregation(name);
            List<StringTerms.Bucket> buckets = stringTerms.getBuckets();
            ArrayList<String> values = new ArrayList<>();
            buckets.forEach(bucket -> values.add(bucket.getKeyAsString()));
            Map<String, Object> map = new HashMap<>();
            map.put("k", name);
            map.put("options", values);
            specList.add(map);
        });
        return specList;
    }

    // 构建基本查询条件
    private QueryBuilder buildBasicQueryWithFilter(SearchRequest request) {
        //创建基本布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 基本查询条件
        queryBuilder.must(QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND));
        // 过滤条件构建器
        BoolQueryBuilder filterQueryBuilder = QueryBuilders.boolQuery();
        // 整理过滤条件
        Map<String, String> filter = request.getFilter();
        for (Map.Entry<String, String> entry : filter.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            // 商品分类和品牌可以直接查询不需要拼接
            if (key != "cid3" && key != "brandId") {
                key = "specs." + key + ".keyword";
            }
            // 字符串类型，进行term查询
            filterQueryBuilder.must(QueryBuilders.termQuery(key, value));
        }
        // 添加过滤条件
        queryBuilder.filter(filterQueryBuilder);
        return queryBuilder;
    }
}
